import type { OrderDetail } from "@/types/order";
import {
  cancelOrder,
  deleteOrder,
  followDoctor,
  getPrescriptionPic,
} from "@/api/consult";
import type { FollowType, ConsultOrderItem } from "@/types/consult";
import { showFailToast, showImagePreview, showSuccessToast } from "vant";
import { OrderType } from "@/enums";
import { onMounted, ref } from "vue";
import { getMedicalOrderDetail } from "@/api/order";

// 封装逻辑，规范 useXxx，表示使用某功能
export const useFollow = (type: FollowType = "doc") => {
  const loading = ref(false);
  // {a, b} 类型，传值得时候 {a, b, c} 也可以，这是类型兼容：多的可以给少的
  const follow = async (obj: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true;
    try {
      await followDoctor(obj.id, type);
      obj.likeFlag = obj.likeFlag === 1 ? 0 : 1;
    } finally {
      loading.value = false;
    }
  };
  return { loading, follow };
};

export const useShowPrescription = () => {
  // 查看处方
  const showPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id);
      showImagePreview([res.data.url]);
    }
  };
  return { showPrescription };
};

// 封装取消订单逻辑
export const useCancelOrder = () => {
  const loading = ref(false);
  const cancelConsultOrder = (item: ConsultOrderItem) => {
    loading.value = true;
    cancelOrder(item.id)
      .then(() => {
        item.status = OrderType.ConsultCancel;
        item.statusValue = "已取消";
        showSuccessToast("取消成功");
      })
      .catch(() => {
        showFailToast("取消失败");
      });
    loading.value = false;
  };
  return { loading, cancelConsultOrder };
};

export const useDeleteOrder = (cb: () => void) => {
  // 删除订单
  const deleteLoading = ref(false);
  const deleteConsultOrder = async (item: ConsultOrderItem) => {
    deleteLoading.value = true;
    try {
      await deleteOrder(item.id);
      // 成功，通知父组件删除这条信息，提示，详情就是跳转列表页面
      showSuccessToast("删除成功");
      cb && cb();
    } catch (e) {
      showFailToast("删除失败");
    }
    deleteLoading.value = false;
  };
  return { deleteLoading, deleteConsultOrder };
};

export const useOrderDetail = (id: string) => {
  const loading = ref(false);
  const order = ref<OrderDetail>();
  onMounted(async () => {
    loading.value = true;
    try {
      const res = await getMedicalOrderDetail(id);
      order.value = res.data;
    } finally {
      loading.value = false;
    }
  });
  return { order, loading };
};
